axios.defaults.baseURL = 'http://192.168.104.217:8280/';
axios.defaults.headers.timeout = 1000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
if (localStorage.getItem("Authorization")) {
    axios.defaults.headers['Authorization'] = "Basic "+localStorage.getItem("Authorization");
} else {
    axios.defaults.headers['Authorization'] = "Basic Y2xpZW50OnNlY3JldA==";
}

function formData(params) {
    var arr = []
    var data = ''
    for (const key in params) {
        if (Object.hasOwnProperty.call(params, key)) {
            const element = params[key];
            arr.push(key + '=' + element)
            data = arr.join('&')
        }
    }
    return data
}

axios.defaults.transformRequest = [function (data) {
    return formData(data);
}];

// `transformResponse` 在传递给 then/catch 前，允许修改响应数据
axios.defaults.transformResponse = [function (data) {
    // 对接收的 data 进行任意转换处理

let params = JSON.parse(data)

        if (params.access_token) {
            console.log(1);
            localStorage.setItem('Authorization', params.access_token)
        }


    return JSON.parse(data);
}];


let loading = document.createElement('div')
loading.style.cssText = "width:100px;height:100px;background:red"
loading.setAttribute('id', 'loading')
// 添加请求拦截器



axios.interceptors.request.use(function (config) {

    document.body.appendChild(loading)
    return config;
}, function (error) {
    document.getElementById('loading').innerHTML = "加载前失败了"
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {

    if (response.data.access_token) {
        console.log(2);
        localStorage.setItem('Authorization', response.data.access_token)
    }

    if (document.getElementById('loading')) {
        document.getElementById('loading').remove()
    } else {
        alert('没有找到loading')
    }

    return response;
}, function (error) {
    document.getElementById('loading').innerHTML = "加载后失败了"
    return Promise.reject(error);
});